//
//  putDynamicVC.m
//  HappyStore
//
//  Created by 陈锋 on 16/7/5.
//  Copyright © 2016年 LLJ. All rights reserved.
//

#import "putDynamicVC.h"
#import "ZipArchive.h"

@interface putDynamicVC ()<UITextViewDelegate,UIActionSheetDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate,TZImagePickerControllerDelegate,UIAlertViewDelegate>{
    NSInteger count;
    NSMutableArray *_selectedAssets;
    
}
@property (weak, nonatomic) IBOutlet UITextView *textview;
@property (strong, nonatomic) NSMutableArray * deleteArr;
@property (strong, nonatomic) NSMutableArray * imgArr;

@property (strong, nonatomic) NSMutableArray * imgViewArr;
@property (nonatomic, strong) UIImagePickerController *imagePickerVc;

@property (strong, nonatomic) UIButton * addBtn;
@property (strong ,nonatomic)UILabel *tip;
@end

@implementation putDynamicVC

- (UIImagePickerController *)imagePickerVc {
    if (_imagePickerVc == nil) {
        _imagePickerVc = [[UIImagePickerController alloc] init];
        _imagePickerVc.delegate = self;
        // set appearance / 改变相册选择页的导航栏外观
        _imagePickerVc.navigationBar.barTintColor = self.navigationController.navigationBar.barTintColor;
        _imagePickerVc.navigationBar.tintColor = self.navigationController.navigationBar.tintColor;
        UIBarButtonItem *tzBarItem, *BarItem;
        if (iOS9Later) {
            tzBarItem = [UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[TZImagePickerController class]]];
            BarItem = [UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[UIImagePickerController class]]];
        } else {
            tzBarItem = [UIBarButtonItem appearanceWhenContainedIn:[TZImagePickerController class], nil];
            BarItem = [UIBarButtonItem appearanceWhenContainedIn:[UIImagePickerController class], nil];
        }
        NSDictionary *titleTextAttributes = [tzBarItem titleTextAttributesForState:UIControlStateNormal];
        [BarItem setTitleTextAttributes:titleTextAttributes forState:UIControlStateNormal];
    }
    return _imagePickerVc;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 44)];
    titleLabel.backgroundColor = [UIColor clearColor];
    titleLabel.font = [UIFont systemFontOfSize:19];
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.text = @"发动态";
    self.navigationItem.titleView = titleLabel;
    //self.title = @"发动态";
    
    //设置返回按钮
    UIBarButtonItem *leftItem = [UIBarButtonItem itemWithTarget:self action:@selector(leftBarButtonItemClick) image:@"Back" highImage:@"Back"];
    self.navigationItem.leftBarButtonItem = leftItem;
    
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithTitle:@"发布" style:UIBarButtonItemStylePlain target:self action:@selector(rightBarButtonItemClick)];
    rightItem.tintColor = [UIColor whiteColor];
    self.navigationItem.rightBarButtonItem = rightItem;
    
    self.imgArr = [NSMutableArray array];
    self.deleteArr = [NSMutableArray array];
    _selectedAssets = [NSMutableArray array];
    
    UIButton * button = [[UIButton alloc]initWithFrame:CGRectMake(10, self.textview.y + self.textview.height + 5, 50, 50)];
    [button setImage:[UIImage imageNamed:@"re_project_add2"] forState:0];
    [button addTarget:self action:@selector(btnClick) forControlEvents:UIControlEventTouchUpInside];
    self.addBtn = button;
    [self.view addSubview:self.addBtn];
    
    self.textview.delegate = self;
    /*自定义文本框placeholder*/
    _tip = [[UILabel alloc]initWithFrame:CGRectMake(10, 3, self.view.width, 25)];
    _tip.text = @"这一刻的想法...";
    _tip.font = [UIFont fontWithName:@"Arial" size:12.0f];
    _tip.backgroundColor = [UIColor clearColor];
    _tip.enabled = NO;
    
    [self.textview addSubview:_tip];
    
    [self.textview becomeFirstResponder];
}

// 自定义文本框placeholder

- (void)textViewDidChange:(UITextView *)textView {

    
    if (self.textview.text.length > 0) {
        _tip.text = @"";
        
    }else{
        _tip.text = @"这一刻的想法...";
    }
}

-(void)rightBarButtonItemClick{
    
    if (self.textview.text.length > 1) {
        
        //token=rE3F2m8AvfC7CVh85O9q&userId=9 参数说明：photo-为图片
        [self showRoundProgressWithTitle:@"请稍后..."];
        self.navigationItem.rightBarButtonItem.enabled = NO;
        NSMutableDictionary *muDicParameters = [NSMutableDictionary dictionary];
        [muDicParameters setObject:[USER_DEFAULTS objectForKey:@"token"] forKey:@"token"];//验证用户
        [muDicParameters setObject:[USER_DEFAULTS objectForKey:@"userid"] forKey:@"userId"];
        [muDicParameters setObject:self.textview.text forKey:@"content"];
        
        NSString *strURl = [NSString stringWithFormat:@"%@%@",URL_DEFINE,@"fabuCibd_app_cibd.im.lensum"];
        
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        
        [manager POST:strURl parameters:muDicParameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
            
            // 压缩
            NSMutableArray *muSaveFull = [NSMutableArray array];
            
            for (int i = 0; i<self.imgArr.count; i++) {
                UIImage *image = self.imgArr[i];
                NSString *strName1 = [NSString stringWithFormat:@"%@.png",[self dateString]];
                [self saveImage:image withName:strName1];
                NSString *fullPath1 = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:strName1];
                [muSaveFull addObject:fullPath1];
            }
            
            
            NSString *zippedPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.zip",[self dateString]]];
            
            BOOL isSucee = [SSZipArchive createZipFileAtPath:zippedPath withFilesAtPaths:muSaveFull];
            if (isSucee) {
                NSData *data1 = [NSData dataWithContentsOfFile:zippedPath];
                [formData appendPartWithFileData:data1 name:@"photos" fileName:@"photos.zip" mimeType:@"zip"];
            }
            
        } progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSDictionary *dicInfo = [NSDictionary dictionaryWithDictionary:responseObject];
            //        NSLog(@"%@",dicInfo);
            if ([dicInfo[@"result"] integerValue] == 1) {
                //                headImg.image = imgUserHeaderImg;
                //                [self.dataDict setObject:dicInfo[@"data"][0] forKey:@"headPhoto"];
                
                [self hideBubble];
                [self.navigationController popViewControllerAnimated:YES];
                self.navigationItem.rightBarButtonItem.enabled = YES;
                
            }else {
                self.navigationItem.rightBarButtonItem.enabled = YES;

                [self showSingleIconBubble:dicInfo[@"msg"]];
            }
  
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            self.navigationItem.rightBarButtonItem.enabled = YES;

            [self showSingleIconBubble:error.localizedDescription];

        }];
        
    }
    
}

-(void)leftBarButtonItemClick{
    
    [self.navigationController popViewControllerAnimated:YES];
    
    
}

-(void)btnClick{
    
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"照片选择"
                                                             delegate:self
                                                    cancelButtonTitle:@"取消"
                                               destructiveButtonTitle:nil
                                                    otherButtonTitles:@"相机",@"相册", nil];
    
    actionSheet.tag = 200;
    [actionSheet showInView:self.view];
    
}

-(void)addImg{
    
    if (self.imgArr.count > 9) {

        [self showSingleIconBubble:@"最多只能添加9张图片"];
        
    }else{
        
        for (int i = 0; i < self.imgViewArr.count; i ++) {
            [self.imgViewArr[i] removeFromSuperview];
            [self.deleteArr [i] removeFromSuperview];
        }
        
        [self.imgViewArr removeAllObjects];
        [self.deleteArr removeAllObjects];
        self.imgViewArr = [NSMutableArray array];
        self.deleteArr = [NSMutableArray array];
        
        for (int i = 0; i < self.imgArr.count; i ++) {
            
            count = i;
            
            UIImageView * imgView = [[UIImageView alloc]init];
            imgView.image = self.imgArr[i];
            imgView.height = 50;
            imgView.width = 50;
            imgView.x = i%5*60+10;
            imgView.y = i/5*60 + self.textview.height +10;
            
            UIButton * deleteBtn = [[UIButton alloc]initWithFrame:CGRectMake(imgView.x - 3, imgView.y - 3, 15, 15)];
            [deleteBtn setImage:[UIImage imageNamed:@"标注"] forState:0];
            [deleteBtn addTarget:self action:@selector(delegateLabel:) forControlEvents:UIControlEventTouchUpInside];
            
            [self.imgViewArr addObject: imgView];
            [self.deleteArr addObject:deleteBtn];
            
            [self.view addSubview:imgView];
            [self.view addSubview:deleteBtn];
            
        }
        
        [self.addBtn removeFromSuperview];
        
        UIImageView * last = self.imgViewArr.lastObject;
        
        UIButton * button = [[UIButton alloc]init];
        
        if (count == 4) {
            
            button.frame = CGRectMake(10 ,60 + self.textview.height +10, 50, 50);
            
        }else if (self.imgArr.count < 1){
            
            button.frame = CGRectMake(10, self.textview.y + self.textview.height + 5, 50, 50);
            
        }else{
            
            button.frame = CGRectMake(last.x + last.width + 10 , last.y, 50, 50);
            
        }
        
        [button setImage:[UIImage imageNamed:@"re_project_add2"] forState:0];
        [button addTarget:self action:@selector(btnClick) forControlEvents:UIControlEventTouchUpInside];
        self.addBtn = button;
        [self.view addSubview:self.addBtn];
        
        
    }
    
}

-(void)delegateLabel:(UIButton *)btn{
    
    for (int i = 0; i < self.imgViewArr.count; i ++) {
        UIImageView * imgView = self.imgViewArr[i];
        
        if (btn.x == imgView.x - 3 && btn.y == imgView.y - 3) {
            [self.imgArr removeObject:imgView.image];
            [_selectedAssets removeObjectAtIndex:i];
        }
    }
    
    [self addImg];
    
}

#pragma mark - 选择照片
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    switch (actionSheet.tag) {
            
        case 200:
        {
            //先设定sourceType为相机，然后判断相机是否可用（ipod）没相机，不可用将sourceType设定为相片库
            UIImagePickerController *pickerImage = [[UIImagePickerController alloc] init];
            pickerImage.delegate = self;
            pickerImage.allowsEditing = YES;//设置可编辑
            switch (buttonIndex) {
                case 0:
                {
                    NSLog(@"相机");
                    //                    pickerImage.sourceType = UIImagePickerControllerSourceTypeCamera;
                    //                    [self presentViewController:pickerImage animated:YES completion:nil];//进入照相界面
                    [self takePhoto];
                }
                    break;
                case 1:
                {
                    NSLog(@"相册");
                    //                    pickerImage.sourceType = UIImagePickerControllerSourceTypePhotoLibrary; //图片库
                    //                    [self presentViewController:pickerImage animated:YES completion:nil];//进入照相界面
                    [self pushImagePickerController];
                }
                    break;
                case 2:
                {
                    NSLog(@"取消");
                }
                    break;
            }
        }
            break;
            
    }
    
}
#pragma mark - TZImagePickerController

- (void)pushImagePickerController {
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:9 delegate:self];
    
#pragma mark - 四类个性化设置，这些参数都可以不传，此时会走默认设置
    imagePickerVc.isSelectOriginalPhoto = YES;
    
    // 1.如果你需要将拍照按钮放在外面，不要传这个参数
    imagePickerVc.selectedAssets = _selectedAssets; // optional, 可选的
    imagePickerVc.allowTakePicture = YES; // 在内部显示拍照按钮
    
    // 2. Set the appearance
    // 2. 在这里设置imagePickerVc的外观
    // imagePickerVc.navigationBar.barTintColor = [UIColor greenColor];
    // imagePickerVc.oKButtonTitleColorDisabled = [UIColor lightGrayColor];
    // imagePickerVc.oKButtonTitleColorNormal = [UIColor greenColor];
    
    // 3. Set allow picking video & photo & originalPhoto or not
    // 3. 设置是否可以选择视频/图片/原图
    imagePickerVc.allowPickingVideo = NO;
    imagePickerVc.allowPickingImage = YES;
    imagePickerVc.allowPickingOriginalPhoto = NO;
    
    // 4. 照片排列按修改时间升序
    imagePickerVc.sortAscendingByModificationDate =YES;
#pragma mark - 到这里为止
    
    // You can get the photos by block, the same as by delegate.
    // 你可以通过block或者代理，来得到用户选择的照片.
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        
    }];
    
    [self presentViewController:imagePickerVc animated:YES completion:nil];
}

#pragma mark - TZImagePickerControllerDelegate

/// User click cancel button
/// 用户点击了取消
// - (void)imagePickerControllerDidCancel:(TZImagePickerController *)picker {
// NSLog(@"cancel");
// }

// The picker should dismiss itself; when it dismissed these handle will be called.
// If isOriginalPhoto is YES, user picked the original photo.
// You can get original photo with asset, by the method [[TZImageManager manager] getOriginalPhotoWithAsset:completion:].
// The UIImage Object in photos default width is 828px, you can set it by photoWidth property.
// 这个照片选择器会自己dismiss，当选择器dismiss的时候，会执行下面的代理方法
// 如果isSelectOriginalPhoto为YES，表明用户选择了原图
// 你可以通过一个asset获得原图，通过这个方法：[[TZImageManager manager] getOriginalPhotoWithAsset:completion:]
// photos数组里的UIImage对象，默认是828像素宽，你可以通过设置photoWidth属性的值来改变它
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto {
    self.imgArr = [NSMutableArray arrayWithArray:photos];
    _selectedAssets = [NSMutableArray arrayWithArray:assets];
    
    [self addImg];
    
}

// If user picking a video, this callback will be called.
// If system version > iOS8,asset is kind of PHAsset class, else is ALAsset class.
// 如果用户选择了一个视频，下面的handle会被执行
// 如果系统版本大于iOS8，asset是PHAsset类的对象，否则是ALAsset类的对象
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingVideo:(UIImage *)coverImage sourceAssets:(id)asset {
    //    self.imgArr = [NSMutableArray arrayWithArray:@[coverImage]];
    _selectedAssets = [NSMutableArray arrayWithArray:@[asset]];
    
    // open this code to send video / 打开这段代码发送视频
    // [[TZImageManager manager] getVideoOutputPathWithAsset:asset completion:^(NSString *outputPath) {
    // NSLog(@"视频导出到本地完成,沙盒路径为:%@",outputPath);
    // Export completed, send video here, send by outputPath or NSData
    // 导出完成，在这里写上传代码，通过路径或者通过NSData上传
    
    // }];
    
    // _collectionView.contentSize = CGSizeMake(0, ((_selectedPhotos.count + 2) / 3 ) * (_margin + _itemWH));
}

#pragma mark - UIImagePickerController

- (void)takePhoto {
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if ((authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied) && iOS8Later) {
        // 无权限 做一个友好的提示
        UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"无法使用相机" message:@"请在iPhone的""设置-隐私-相机""中允许访问相机" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"设置", nil];
        [alert show];
    } else { // 调用相机
        UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
        if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
            self.imagePickerVc.sourceType = sourceType;
            if(iOS8Later) {
                _imagePickerVc.modalPresentationStyle = UIModalPresentationOverCurrentContext;
            }
            self.tabBarController.tabBar.hidden = YES;
            [self presentViewController:_imagePickerVc animated:YES completion:nil];
        } else {
            NSLog(@"模拟器中无法打开照相机,请在真机中使用");
        }
    }
}

#pragma mark - UIAlertViewDelegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 1) { // 去设置界面，开启相机访问权限
        if (iOS8Later) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
        } else {
            // [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root=Privacy&path=Photos"]];
        }
    }
}

- (void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:nil];
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    if ([type isEqualToString:@"public.image"]) {
        TZImagePickerController *tzImagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:9 delegate:self];
        tzImagePickerVc.sortAscendingByModificationDate = YES;
        [tzImagePickerVc showProgressHUD];
        UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
        // save photo and get asset / 保存图片，获取到asset
        [[TZImageManager manager] savePhotoWithImage:image completion:^{
            [[TZImageManager manager] getCameraRollAlbum:NO allowPickingImage:YES completion:^(TZAlbumModel *model) {
                [[TZImageManager manager] getAssetsFromFetchResult:model.result allowPickingVideo:NO allowPickingImage:YES completion:^(NSArray<TZAssetModel *> *models) {
                    [tzImagePickerVc hideProgressHUD];
                    TZAssetModel *assetModel = [models firstObject];
                    if (tzImagePickerVc.sortAscendingByModificationDate) {
                        assetModel = [models lastObject];
                    }
                    [_selectedAssets addObject:assetModel.asset];
                    [_imgArr addObject:image];
                    [self addImg];
                }];
            }];
        }];
        
    }
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    self.tabBarController.tabBar.hidden = NO;
    [picker dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark 照片的时间名称
- (NSString*)dateString
{
    NSMutableString*string=[[NSMutableString alloc] init];
    NSDate*dayDate=[NSDate date];
    NSDateFormatter*dayFormatter=[[NSDateFormatter alloc] init];
    [dayFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString *dateStrings= [dayFormatter stringFromDate:dayDate];
    NSArray*dayArray=[dateStrings componentsSeparatedByString:@"-"];
    for (int i=0; i<[dayArray count]; i++) {
        [string appendFormat:@"%@",[dayArray objectAtIndex:i]];
    }
    NSDate*timeDate=[NSDate date];
    NSDateFormatter*timeFormatter=[[NSDateFormatter alloc] init];
    [timeFormatter setDateFormat:@"HH:mm:ss:SSS"];
    NSString *timeString= [timeFormatter stringFromDate:timeDate];
    NSArray*timeArray=[timeString componentsSeparatedByString:@":"];
    for (int i=0; i<[timeArray count]; i++) {
        [string appendFormat:@"%@",[timeArray objectAtIndex:i]];
    }
    return string;
    
}
#pragma mark - 保存图片至沙盒
- (void) saveImage:(UIImage *)currentImage withName:(NSString *)imageName
{
    NSData *imageData = UIImageJPEGRepresentation(currentImage, 0.1);
    // 获取沙盒目录
    NSString *fullPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:imageName];
    // 将图片写入文件
    [imageData writeToFile:fullPath atomically:NO];
}
@end
